/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.Country;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Institution;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author santiagobaldrich
 */
public class CountryJpaController {

    public CountryJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Country country)
    {
        if (country.getInstitutionCollection() == null)
        {
            country.setInstitutionCollection(new ArrayList<Institution>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Institution> attachedInstitutionCollection = new ArrayList<Institution>();
            for (Institution institutionCollectionInstitutionToAttach : country.getInstitutionCollection())
            {
                institutionCollectionInstitutionToAttach = em.getReference(institutionCollectionInstitutionToAttach.getClass(), institutionCollectionInstitutionToAttach.getIdInstitution());
                attachedInstitutionCollection.add(institutionCollectionInstitutionToAttach);
            }
            country.setInstitutionCollection(attachedInstitutionCollection);
            em.persist(country);
            for (Institution institutionCollectionInstitution : country.getInstitutionCollection())
            {
                Country oldCountryOfInstitutionCollectionInstitution = institutionCollectionInstitution.getCountry();
                institutionCollectionInstitution.setCountry(country);
                institutionCollectionInstitution = em.merge(institutionCollectionInstitution);
                if (oldCountryOfInstitutionCollectionInstitution != null)
                {
                    oldCountryOfInstitutionCollectionInstitution.getInstitutionCollection().remove(institutionCollectionInstitution);
                    oldCountryOfInstitutionCollectionInstitution = em.merge(oldCountryOfInstitutionCollectionInstitution);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Country country) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Country persistentCountry = em.find(Country.class, country.getIdCountry());
            Collection<Institution> institutionCollectionOld = persistentCountry.getInstitutionCollection();
            Collection<Institution> institutionCollectionNew = country.getInstitutionCollection();
            List<String> illegalOrphanMessages = null;
            for (Institution institutionCollectionOldInstitution : institutionCollectionOld)
            {
                if (!institutionCollectionNew.contains(institutionCollectionOldInstitution))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Institution " + institutionCollectionOldInstitution + " since its country field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Institution> attachedInstitutionCollectionNew = new ArrayList<Institution>();
            for (Institution institutionCollectionNewInstitutionToAttach : institutionCollectionNew)
            {
                institutionCollectionNewInstitutionToAttach = em.getReference(institutionCollectionNewInstitutionToAttach.getClass(), institutionCollectionNewInstitutionToAttach.getIdInstitution());
                attachedInstitutionCollectionNew.add(institutionCollectionNewInstitutionToAttach);
            }
            institutionCollectionNew = attachedInstitutionCollectionNew;
            country.setInstitutionCollection(institutionCollectionNew);
            country = em.merge(country);
            for (Institution institutionCollectionNewInstitution : institutionCollectionNew)
            {
                if (!institutionCollectionOld.contains(institutionCollectionNewInstitution))
                {
                    Country oldCountryOfInstitutionCollectionNewInstitution = institutionCollectionNewInstitution.getCountry();
                    institutionCollectionNewInstitution.setCountry(country);
                    institutionCollectionNewInstitution = em.merge(institutionCollectionNewInstitution);
                    if (oldCountryOfInstitutionCollectionNewInstitution != null && !oldCountryOfInstitutionCollectionNewInstitution.equals(country))
                    {
                        oldCountryOfInstitutionCollectionNewInstitution.getInstitutionCollection().remove(institutionCollectionNewInstitution);
                        oldCountryOfInstitutionCollectionNewInstitution = em.merge(oldCountryOfInstitutionCollectionNewInstitution);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = country.getIdCountry();
                if (findCountry(id) == null)
                {
                    throw new NonexistentEntityException("The country with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Country country;
            try
            {
                country = em.getReference(Country.class, id);
                country.getIdCountry();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The country with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Institution> institutionCollectionOrphanCheck = country.getInstitutionCollection();
            for (Institution institutionCollectionOrphanCheckInstitution : institutionCollectionOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Country (" + country + ") cannot be destroyed since the Institution " + institutionCollectionOrphanCheckInstitution + " in its institutionCollection field has a non-nullable country field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(country);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Country> findCountryEntities()
    {
        return findCountryEntities(true, -1, -1);
    }

    public List<Country> findCountryEntities(int maxResults, int firstResult)
    {
        return findCountryEntities(false, maxResults, firstResult);
    }

    private List<Country> findCountryEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Country.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Country findCountry(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Country.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getCountryCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Country> rt = cq.from(Country.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public Country getCountryByName(String name)
    {
        EntityManager em = null;
        Country c = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Country.findByName");
            q.setParameter("name", name);
            c = (Country) q.getSingleResult();
        } catch (Exception e)
        {
            c = null;
        } finally
        {
            em.close();
            return c;
        }
    }

    public List<Country> findAll()
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q = em.createNamedQuery("Country.findAll");
            return (List<Country>)q.getResultList();
        } catch (Exception e)
        {
            System.out.println("Exception at ContryJPAController.findAll: " + e.getMessage());
            return null;
        }
    }
}
